import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/gen_a/A.dart';
import 'package:exams_app/home_module/account_set_module/about_page.dart';
import 'package:exams_app/home_module/exams_module/view.dart';
import 'package:exams_app/login_module/register/register_page.dart';
import 'package:exams_app/login_module/seturl_page.dart';
import 'package:exams_app/widget/hexcolor.dart';
import 'package:exams_app/widget/webview_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rtmp_publisher/camera.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../main.dart';
import 'code_login_view.dart';
import 'logic.dart';




class LoginTabContainer extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState

    return LoginTabContainerState();
  }
}

class LoginTabContainerState extends State<LoginTabContainer> with TickerProviderStateMixin {


  final LoginModuleLogic logic = Get.put(LoginModuleLogic());

  TabController _controller;

  var _username = TextEditingController();

  var _pwd = TextEditingController();

  bool check = false;


  CameraController controller;

  void initState() {
    // TODO: implement initState
    _controller = TabController(length: 2, vsync: this);

    super.initState();

    initUrl();



    controller = CameraController(cameras[1], ResolutionPreset.medium);

    controller.initialize().then((_) {
      if (!mounted) {

        return;
      }
      setState(() {});
    });
  }

  void initUrl()async{

    // 如果为空,去取值
    var prefs = await SharedPreferences.getInstance();
    if(prefs.getString('urlStr')==null){
      prefs.setString('urlStr', 'http://36.153.159.19:8072');
    }
    check = prefs.getBool('check');

    _username.text = prefs.get('username');
    _pwd.text = prefs.get('pwd');

    // if(check == true){
    //   _username.text = prefs.get('username');
    //   _pwd.text = prefs.get('pwd');
    // }
  }

  /// 记住密码
  void getUsernameAndPassWord() async {
    var prefs = await SharedPreferences.getInstance();
    prefs.setString('username', _username.text);
    prefs.setString('pwd', _pwd.text);
    prefs.setBool('check', true);
  }

  /// 清除密码
  void clearUserNameAndPassWord() async {
    var prefs = await SharedPreferences.getInstance();
    prefs.remove('username');
    prefs.remove('pwd');
    _username.text = '';
    _pwd.text = '';
    prefs.setBool('check', false);
    // check = false;
  }

  @override

  Widget build(BuildContext context) {
    // TODO: implement build
    DateTime _lastPressedAt; //上次点击时间


    return new WillPopScope(
      onWillPop: () async {
        if (_lastPressedAt == null ||
            DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)) {

          BotToast.showText(text: '再按一次退出程序');
          //两次点击间隔超过1秒则重新计时
          _lastPressedAt = DateTime.now();
          return false;
        }
        return true;
      },
      child:  Expanded(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top:15 ),
              width: Get.width,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(0.0),
                  boxShadow: [
                    BoxShadow(
                        color: HexColor('#ECECEC'),
                        offset: Offset(1.0, 5.0), //阴影xy轴偏移量
                        blurRadius: 10.0, //阴影模糊程度
                        spreadRadius: 1.0 //阴影扩散程度
                    )
                  ]),
              child: TabBar(
                isScrollable: true,
                controller: _controller,
                labelStyle: TextStyle(
                    fontSize: 14,
                    color: HexColor('#567BFD'),
                    fontWeight: FontWeight.w600),
                labelColor: HexColor('#567BFD'),

                unselectedLabelStyle: TextStyle(fontSize: 14, color: HexColor('567BFD')),
                unselectedLabelColor: HexColor('#999999'),
                // indicatorSize: TabBarIndicatorSize.label,
                indicator: MyUnderlineTabIndicator(
                    borderSide:
                    BorderSide(width: 2.0, color: HexColor('#567BFD'))),
                indicatorColor: HexColor('#567BFD'),
                // indicator: const BoxDecoration(),

                tabs: [
                  Tab(
                    text: '账号登录',
                  ),
                  Tab(
                    text: '验证码登录',
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                child: TabBarView(
                  controller: _controller,
                  children: [
                    ListView(
                      children: [
                        Center(
                          child: Container(
                            decoration: new BoxDecoration(
                              color: Colors.transparent,
                              //设置四周圆角 角度
                              borderRadius: BorderRadius.all(Radius.circular(25.0)),
                              //设置四周边框
                              border: new Border.all(width: 1, color: HexColor('#ECECEC')),

                            ),
                            padding: EdgeInsets.only(left: 15),
                            margin: EdgeInsets.only(top: 20,left: 15,right: 15),
                            // width: Get.width-100,
                            child:
                            TextField(
                              autofocus: true,
                              controller: _username,
                              style: TextStyle(fontSize: 16),
                              decoration: InputDecoration(
                                // isCollapsed: true,
                                // contentPadding: EdgeInsets.only(top: 15),
                                hintText: '请输入账号/手机号',
                                hintStyle: TextStyle(fontSize: 16,color: HexColor('#BBBBBB')),
                                border: InputBorder.none,
                                // prefixIcon: Image.asset(A.assets_user,),
                              ),
                            ),
                          ),
                        ),
                        Center(
                          child: Container(
                            decoration: new BoxDecoration(
//背景
                              color: Colors.white,
                              //设置四周圆角 角度
                              borderRadius: BorderRadius.all(Radius.circular(25.0)),
                              //设置四周边框
                              border: new Border.all(width: 1, color: Colors.grey[200]),
                            ),

                            padding: EdgeInsets.only(left: 15),
                            margin: EdgeInsets.only(top: 10, right: 15, left: 15),
                            child: TextField(
                              obscureText: true,
                              controller: _pwd,
                              style: TextStyle(fontSize: 16),
                              decoration: InputDecoration(
                                // contentPadding: EdgeInsets.only(top: 15),
                                hintText: '请输入密码',
                                hintStyle: TextStyle(fontSize: 16,color: HexColor('#BBBBBB')),
                                border: InputBorder.none,
                                // prefixIcon: Image.asset(A.assets_pwd),
                              ),
                            ),
                          ),
                        ),

                       Container(
                         margin: EdgeInsets.only(right: 25),
                         child:  Row(
                           mainAxisAlignment:MainAxisAlignment.spaceBetween,
                           children: [
                             GestureDetector(
                               child: Container(
                                 padding: EdgeInsets.only(left: 25,top: 15),
                                 // color: Colors.red,
                                 child: Text('注册账号',style: TextStyle(color: Theme.of(context).primaryColor),),

                               ),
                               onTap: (){
                                 Get.to(RegisterPage());
                               },
                             ),
                             GestureDetector(
                               child: Container(
                                 padding: EdgeInsets.only(left: 25,top: 15),
                                 // color: Colors.red,
                                 child: Text('使用手册',style: TextStyle(color: Theme.of(context).primaryColor),),

                               ),
                               onTap: (){
                                 // Get.to(RegisterPage());
                                 // Get.to(MyWebView(title: '使用说明',url: 'https://live.bilibili.com/23805516',));
                                 Get.to(MyWebView(title: '使用说明',url: 'https://docs.qq.com/s/BQ_PtGtdzuKjNqyOMMSD0a',));

                               },
                             ),
                           ],
                         ),
                       ),

                        Container(
                          margin: EdgeInsets.only(top: 62, right: 15, left: 15),
                          width: Get.width,
                          height: 45,
                          child:
                          RaisedButton(
                            elevation: 0,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(22),
                            ),
                            color: Theme.of(context).primaryColor,
                            onPressed: () async {

                              // Get.dialog(CupertinoAlertDialog(
                              //   title: Text('111'),
                              //   content: Text('11'),
                              //   actions: [
                              //     FlatButton(onPressed: (){}, child: Text('yes')),
                              //     FlatButton(onPressed: (){}, child: Text('no'))
                              //   ],
                              // ));

                             // Get.dialog( AlertDialog(
                             //   title: Text('accept?'),
                             //   content: Text('do you accept?'),
                             //   actions: [
                             //     FlatButton(onPressed: (){}, child: Text('yes')),
                             //     FlatButton(onPressed: (){}, child: Text('no'))
                             //   ],
                             //   elevation: 25,
                             // ));

                              var prefs = await SharedPreferences.getInstance();

                              // Get.offAll(AboutPage());

                              if (prefs.getString('urlStr') == null) {

                                BotToast.showText(text: '请先设置BaseUrl');
                                return;
                              }
                              print(prefs.getString('urlStr'));



                              if (_username.text.isEmpty || _pwd.text.isEmpty) {
                                BotToast.showText(text: '请输入账号密码');
                                // Toast.toast(context, msg: '请输入账号密码');

                                return;
                              }

                              prefs.setString('username', _username.text);
                              prefs.setString('pwd', _pwd.text);

                              logic.requestData(_username.text, _pwd.text);

                              FocusScope.of(context).requestFocus(FocusNode());

                              if (check == true) {
                                // getUsernameAndPassWord();
                              }
                            },
                            child: Text(
                              '登录',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        ),
                       Center(
                         child:  Container(


                           margin: EdgeInsets.only(top: 10, right: 20, left: 30),
                           child: Row(
                             mainAxisAlignment:MainAxisAlignment.center,
                             children: [
                               Text('阅读',style: TextStyle(fontSize: 12),),
                               GestureDetector(
                                 child:  Text('《用户协议》',style: TextStyle(fontSize: 12,color: Theme.of(context).primaryColor)),
                                 onTap: (){
                                   Get.to(MyWebView(url: 'https://docs.qq.com/doc/DUUZSZW5la3FySVhP', title: '用户协议'));
                                 },
                               ),
                               GestureDetector(
                                 child: Text('《个人信息保护政策》',style: TextStyle(fontSize: 12,color: Theme.of(context).primaryColor)),
                                 onTap: (){
                                   Get.to(MyWebView(url: 'https://docs.qq.com/doc/DUU5JemFJc2ZwWHFU', title: '个人信息保护政策'));

                                 },
                               )
                             ],
                           ),
                         ),
                       ),

                        Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(left: 25, top: 10, right: 25),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  // Container(
                                  //   child: Checkbox(
                                  //     value: this.check,
                                  //     onChanged: (value) async {
                                  //       if (value == true) {
                                  //         // getUsernameAndPassWord();
                                  //       } else {
                                  //         // clearUserNameAndPassWord();
                                  //       }
                                  //
                                  //       setState(() {
                                  //         this.check = value;
                                  //       });
                                  //     },
                                  //   ),
                                  // ),
                                  // CupertinoButton(
                                  //     child: Container(
                                  //       decoration: BoxDecoration(
                                  //           color: check
                                  //               ? Theme.of(context).primaryColor
                                  //               : CupertinoColors.white,
                                  //           border: Border.all(
                                  //               color: HexColor('#D0D0D0'),
                                  //               style: BorderStyle.solid,
                                  //               width: 1),
                                  //           borderRadius: BorderRadius.all(Radius.circular(5))),
                                  //       child: Icon(check?CupertinoIcons.checkmark_alt:null,
                                  //           size: 20,
                                  //           color: check
                                  //               ? CupertinoColors.white
                                  //               : HexColor('#D0D0D0')),
                                  //     ),
                                  //
                                  //     onPressed: ()async {
                                  //             if (check == true) {
                                  //               getUsernameAndPassWord();
                                  //             } else {
                                  //               // clearUserNameAndPassWord();
                                  //             }
                                  //       setState(() {
                                  //         check = !check;
                                  //       });
                                  //     }
                                  // ),
                                  // Text(
                                  //   '记住密码',
                                  //   style: TextStyle(fontSize: 14,color: HexColor('#333333')),
                                  // ),
                                ],
                              ),
                            ],
                          ),
                        ),

                      ],
                    ),
                    CodeLoginPage(),
                  ],
                ),
              ),),
          ],
        ),
      ),
    );


  }

}

// class LoginModulePage extends StatefulWidget {
//   @override
//   _LoginModulePageState createState() => _LoginModulePageState();
// }

class LoginModulePage extends StatelessWidget {

  final LoginModuleLogic logic = Get.put(LoginModuleLogic());

  @override



    Widget build(BuildContext context) {
      return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          actions: [
            IconButton(icon:Image.asset(A.assets_setting_icon), onPressed: (){
              Get.to(SetUrlPage());
            })
          ],
          backgroundColor: Colors.white,
          elevation: 0,
        ),
        body:  Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              // color: Colors.red,
                padding: EdgeInsets.only(top: 25, left:15, right: 15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            // Image.asset(A.assets_009,width: 50,height: 50,),

                            Container(
                              margin: EdgeInsets.only(left: 8),
                              child: Text(
                                '登录考试系统',
                                style: TextStyle(
                                    fontSize: 22,
                                    color: HexColor('#333333'),
                                    fontWeight: FontWeight.w600),
                              ),
                            )
                          ],
                        )
                        // Container(
                        //   margin: EdgeInsets.only(top: 5),
                        //   child: Text(
                        //     '海量教学课程,视频',
                        //     style: TextStyle(
                        //         fontSize: 12,
                        //         color: HexColor('#999999'),
                        //         fontWeight: FontWeight.w400),
                        //   ),
                        // )
                      ],
                    ),
                    // Image.asset(A.assets_loginright)
                  ],
                )),
            LoginTabContainer(),
          ],
        ),
      );

    }
}